<template>
    <!-- 搜索与操作区 -->
    <div style="display: flex">
        <el-button type="primary" style="margin-right: 15px  " @click="addItem">新增</el-button>
        <el-input v-model="search" placeholder="请输入教案名称"
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px;" clearable />
        <el-select v-model='searchCourseId' placeholder="请选择课程名称" filterable clearable
            style="width: 200px;height: 33px;margin-right: 15px;font-size: 15px">

            <el-option v-for="item in courseOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-button type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;"
            @click="load">查询</el-button>
    </div>

    <el-table :data="tableData" :row-style="{ height: '77px' }"
        style="width: calc(100vw - 240px);height: 75vh;margin-top: 20px;font-size: 15px;" border>
        <!-- 各列定义 -->
        <el-table-column prop="name" label="教案名称" width="auto" align="center" />
        <el-table-column prop="courseName" label="课程名称" width="auto" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="auto" align="center" />
        <el-table-column label="操作" fixed="right" width="200" align="center">
            <template v-slot="scope">
                <div>
                    <el-button icon="Edit" size="small" type="primary" @click="editItem(scope.row)">编辑</el-button>
                    <el-button icon="View" size="small" type="success" @click="openFile(scope.row.url)">查看</el-button>
                </div>
                <div>
                    <el-button icon="Download" size="small" type="warning"
                        @click="download(scope.row.url)">下载</el-button>
                    <el-button icon="Delete" size="small" type="danger" @click="deleteItem(scope.row.id)">删除</el-button>
                </div>
            </template>
        </el-table-column>
    </el-table>

    <!--      分页-->
    <div style="margin-top: 10px">
        <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" :background="true"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <el-dialog :close-on-click-modal="false" title="文件操作" v-model="dialogVisible" width="560" @close="reset('form')">
        <el-form label-position="top" :inline="true" :model="form" ref="form" :rules="rules">
            <!--输入用户名-->
            <el-form-item label="教案名称" prop="name">
                <el-input placeholder="请输入教案名称" v-model="form.name" autocomplete="off" clearable></el-input>
            </el-form-item>
            <el-form-item label="课程名称" prop="courseId">
                <el-select v-model="form.courseId" filterable clearable placeholder="请选择课程名称" style="width: 185px">
                    <el-option v-for="item in courseOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="上传文件" prop="url">
                <el-upload :before-upload="checkFileType" class="avatar-uploader" :action="'/api/files/upload'"
                    :on-success="photoHandleSuccess" :on-error="photoHandleError" :show-file-list="false">
                    <el-button size="center" type="primary">上传</el-button>
                    <el-button size="small" type="danger" v-if="form.url" @click="deleteImage">删除</el-button>
                </el-upload>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="reset('form')">取 消</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>

    <el-dialog title="文件预览" v-model="openItemFileDialog" width="70%" top="5vh" class="custom-preview-dialog"
        @close="closeFile">
        <div class="preview-container" v-if="openItemFileDialog">
            <!-- PDF 预览 -->
            <vue-office-pdf v-if="fileExt === 'docx' || fileExt === 'doc'" :src="pdfSrc" style="height: 600px" />

            <iframe v-if="fileExt !== 'docx' && fileExt !== 'doc'" :src="pdfSrc" frameborder="0"
                style="background-color: #fff;width: 100%; height: 600px"></iframe>
        </div>
    </el-dialog>

</template>

<script>
import { serverIp } from "~/utils/config.js"
import request from "~/utils/request.js";
import VueOfficePdf from '@vue-office/pdf'
export default {
    components: {
        VueOfficePdf
    },
    data() {
        return {
            openItemFileDialog: false,
            dialogVisible: false,
            serverIp: serverIp, //附件上传路径
            pdfSrc: "",
            fileExt: '',       // 文件扩展名
            form: {},
            courseOptions: [],
            searchCourseId: '',
            tableData: [],
            search: '',
            currentPage: 1,
            pageSize: 10,
            total: 0,
            rules: {
                name: [
                    { required: true, message: '请输入教案名称', trigger: 'blur' },
                ],
                courseId: [
                    { required: true, message: '请选择课程名称', trigger: 'blur' },
                ]
            },
        }
    },
    async created() {
        await this.getCourseOptions(); // 先获取课程选项
        await this.load(); // 加载数据
    },
    methods: {
        async load() {
            // 然后检查路由参数
            if (this.$route.query.courseId === undefined && this.searchCourseId === undefined) {
                this.searchCourseId = ''
            } else if (this.$route.query.courseId !== undefined) {
                this.searchCourseId = Number(this.$route.query.courseId)
            }
            request.get("/lesson-note/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&name=" + this.search + "&courseId=" + this.searchCourseId).then(res => {
                if (res.code === '200') {
                    for (let key in res.data) {
                        if (key === "records") {
                            this.tableData = res.data[key];
                        } else if (key === "total") {
                            this.total = res.data[key];
                        }
                    }
                } else {
                    ElMessage.error("错误" + res.msg)
                }
            })
        },
        async getCourseOptions() {
            return request.get("/course/all").then(res => {
                this.courseOptions = res.data;
            });
        },
        getCourseName(courseId) {
            if (!courseId) return '';
            // 确保courseId与选项中的类型一致
            const id = typeof courseId === 'string' ? courseId : String(courseId);
            const course = this.courseOptions.find(item => String(item.id) === id);
            return course ? course.name : '未知课程';
        },
        download(url) {
            const fileName = `${encodeURIComponent(url.split('/').pop())}`
            window.open(serverIp + "/api/files/download/" + fileName)
        },
        editItem(item) {
            Object.assign(this.form, item)
            this.dialogVisible = true
        },
        addItem() {
            this.dialogVisible = true;
        },
        // 删除
        deleteItem(scope) {
            this.$confirm('是否确定删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                request.get("/lesson-note/delete/" + scope).then(res => {
                    if (res.code === '200') {
                        this.$message.success("成功")
                        this.load()
                    } else {
                        this.$message.error(res.msg)
                    }
                })
            });
        },
        // 提交
        submitForm(val) {
            this.$refs[val].validate((valid) => {
                if (valid) {
                    request.post("/lesson-note/edit", this.form).then(res => {
                        if (res.code === '200') {
                            this.$message({
                                message: "成功",
                                type: "success"
                            })
                            this.load()
                            this.reset(val)
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                }
            })
        },
        // 取消
        reset(val) {
            this.dialogVisible = false;
            this.form = {};
            this.$refs[val].resetFields();
        },
        handleCurrentChange(item) {
            // 改变当前页码触发
            this.currentPage = item
            this.load()
        },
        handleSizeChange(item) {   // 改变当前每页的个数触发
            this.pageSize = item
            this.load()
        },
        checkFileType(file) {
            const maxSize = 1024 * 1024 * 1024;
            if (file.size > maxSize) {
                this.$message.warning('文件大小超过1GB限制!');
                return false;
            }
            return true;
        },
        photoHandleSuccess(response) {
            this.form.url = `/api/file/download/${response}`
            this.$message.success('上传成功');
        },
        photoHandleError() {
            this.$message.error("上传文件失败")
        },
        deleteImage() {
            this.form.url = '';
            this.$message.success('删除成功');
        },
        async openFile(fileUrl) {
            this.openItemFileDialog = true
            const fullUrl = serverIp + fileUrl
            this.fileExt = fileUrl.split('.').pop().toLowerCase()
            console.log(this.fileExt)
            try {
                if (this.fileExt !== "docx" && this.fileExt !== "doc") {
                    this.pdfSrc = fullUrl
                } else {
                    const previewUrl = `/api/files/preview/${encodeURIComponent(fileUrl.split('/').pop())}`
                    const response = await fetch(previewUrl)
                    const blob = await response.blob()
                    this.pdfSrc = URL.createObjectURL(blob)
                }
            } catch (error) {
                this.$message.error('文档预览失败: ' + error.message)
            }
        },
        handleClear() {
            this.searchCourseId = ''
            this.$route.query.courseId = ''
        },
        closeFile() {
            this.openItemFileDialog = false
            // 释放URL对象
            if (this.pdfSrc && this.pdfSrc.startsWith('blob:')) {
                URL.revokeObjectURL(this.pdfSrc);
            }
            this.pdfSrc = "";

            // 销毁iframe的资源
            const iframes = document.querySelectorAll('iframe');
            iframes.forEach(iframe => {
                iframe.src = 'about:blank';
            });
        },
    }
}
</script>

<style scoped>
::v-deep .custom-preview-dialog {
    /* 限制弹窗最大高度为视口的90% */
    max-height: 90vh;
    display: flex;
    flex-direction: column;
}

/* 内容容器 */
::v-deep .custom-preview-dialog .el-dialog__body {
    flex: 1;
    padding: 0 !important;
    /* 移除默认padding */
    overflow: hidden;
    /* 隐藏溢出内容 */
}

.preview-container {
    height: 100%;
    display: flex;
    flex-direction: column;
}

/* Office内容区域 */
.office-content {
    flex: 1;
    /* 填充剩余空间 */
    min-height: 400px;
    /* 最小高度保证 */
    overflow: auto;
    /* 添加滚动条 */
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 20px;
    background: white;
}

.office-content {
    word-wrap: break-word;
    overflow-wrap: break-word;
}

/* 调整TXT预览样式 */
pre {
    flex: 1;
    overflow: auto;
    margin: 0;
    background: white;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}
</style>
